// v2010.09.21

/*
Copyright (c) 2010 Ben Hendel-Doying

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package world;

public class Rectangle
{
	protected Coordinate upper_left;
	protected Coordinate lower_right;

	Rectangle()
	{
		upper_left = new Coordinate();
		lower_right = new Coordinate();
	}

	Rectangle(Rectangle t)
	{
		upper_left = new Coordinate(t.upper_left);
		lower_right = new Coordinate(t.lower_right);
	}

	Rectangle(Coordinate l, int w, int h)
	{
		upper_left = new Coordinate(l);
		lower_right = new Coordinate(l.GetX() + w - 1, l.GetY() + h - 1);
	}

	Rectangle(int x, int y, int w, int h)
	{
		upper_left = new Coordinate(x, y);
		lower_right = new Coordinate(x + w - 1, y + h - 1);
	}

	final public int GetX() { return upper_left.GetX(); }
	final public int GetY() { return upper_left.GetY(); }
	final public int GetX2() { return lower_right.GetX(); }
	final public int GetY2() { return lower_right.GetY(); }
	final public int GetWidth() { return lower_right.GetX() - upper_left.GetX() + 1; }
	final public int GetHeight() { return lower_right.GetY() - upper_left.GetY() + 1; }

	final public Coordinate GetUpperLeft() { return upper_left; }

	final public void MoveTo(int new_x, int new_y)
	{
		final int dx = new_x - upper_left.GetX();
		final int dy = new_y - upper_left.GetY();

		upper_left.Shift(dx, dy);
		lower_right.Shift(dx, dy);
	}

	public final Rectangle IntersectionWith(Rectangle t)
	{
		final int x1 = Math.max(GetX(), t.GetX());
		final int y1 = Math.max(GetY(), t.GetY());
		final int x2 = Math.min(GetX2(), t.GetX2());
		final int y2 = Math.min(GetY2(), t.GetY2());

		if(x2 > x1 && y2 > y1)
			return new Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
		else
			return null;
	}
}
